﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace UpLoadApi.Controllers
{
    public class UploadMultiPartController : ApiController
    {
        [HttpGet]
        public string Get()
        {
            return "Hello!This is UploadMultiPart!";
        }

        [HttpPost]
        public async Task<string> Post()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            Dictionary<string, string> dic = new Dictionary<string, string>();
            //string root = HttpContext.Current.Server.MapPath("~/App_Data");//指定要将文件存入的服务器物理位置 
            string root = "E:/UpLoad/Server";
            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }
            var provider = new MultipartFormDataStreamProvider(root);
            try
            {
                // Read the form data.  
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.  
                foreach (MultipartFileData file in provider.FileData)
                {//接收文件  
                    Trace.WriteLine(file.Headers.ContentDisposition.FileName);//获取上传文件实际的文件名  
                    Trace.WriteLine("Server file path: " + file.LocalFileName);//获取上传文件在服务上默认的文件名  
                }//这样做直接就将文件存到了指定目录下，只接收文件数据流可通过HttpFileCollection操作 但并不保存至服务器的目录下，由开发自行指定如何存储，比如通过服务存到图片服务器  
                foreach (var key in provider.FormData.AllKeys)
                {//接收FormData  
                    dic.Add(key, provider.FormData[key]);
                }
            }
            catch(Exception ex)
            {
                return "Failed "+ex.Message;
                throw;
            }
            return "Success";
        }

        [HttpPost]
        [ActionName("UploadFile")]
        public string UploadFile()
        {
            //文件保存的服务器路径
            string root = "E:/UpLoad/Server/";
            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }

            HttpRequest request = System.Web.HttpContext.Current.Request;
            //保存表单数据
            Dictionary<string, string> dic = new Dictionary<string, string>();
            var formData = request.Form;
            for (int i=0;i< formData.Count;i++)
            {
                string keyName = formData.GetKey(i);
                dic.Add(keyName, formData.Get(keyName));
            }
            //保存文件数据
            HttpFileCollection FileCollect = request.Files;           
            if (FileCollect.Count > 0)          //如果集合的数量大于0
            {
                foreach (string str in FileCollect)
                {
                    HttpPostedFile File = FileCollect[str];  //用key获取单个文件对象HttpPostedFile
                    //得到文件数据流，可以进行其他转存操作
                    Stream FileStream = File.InputStream;

                    string AbsolutePath = root + File.FileName;
                    File.SaveAs(AbsolutePath);              //将上传的东西保存
                }
            }

            string res = JsonConvert.SerializeObject(dic);
            return res;
        }
    }
}
